<?php

namespace backend\modules\rbac\models;

class Role extends AuthItem
{
    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'name' => '名称',
            'permissions' => '权限',
            'description' => '描述',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public function rules()
    {
        $rules = parent::rules();
        $rules[] = [['permissions'], 'safe'];
        return $rules;
    }

    public function getPermissions()
    {
        return AuthItemChild::find()->where(['parent'=>$this->name])->select(['child'])->column();
    }

    public function setPermissions($value)
    {
        $this->permissions = $value?$value:[];
    }

    public static function savePermissions($parent, $permissions = [])
    {
        $old = AuthItemChild::find()->where(['parent'=>$parent])->select(['child'])->column();
        $cut = array_diff($old, $permissions);
        $add = array_diff($permissions, $old);
        //保存一下授权
        AuthItemChild::getDb()->transaction(function () use($cut, $add, $parent){
            AuthItemChild::deleteAll(['parent'=>$parent, 'child'=>$cut]);
            $obj = new AuthItemChild();
            foreach ($add as $value){
                $obj->setIsNewRecord(true);
                $obj->parent = $parent;
                $obj->child = $value;
                $obj->save();
            }
        });
    }
}
